angular
    .module("Ajani.directives", [])
    .directive("navList", () ->
        (scope, elm, attrs)->
            isHome = attrs.navList
            scope.$watch isHome, (newValue, oldValue) ->
                # console.log newValue
                # console.log scope.navi.first
                if not scope.navi.first
                    if not scope.navi.second
                        if newValue
                            elm.css 'display', 'none'
                        else
                            elm.css 'display', 'list-item'
                    scope.navi.second = false
                scope.navi.first = false
    )
    .directive("eatClick", ()->
        (scope, elm, attrs)->
            elm.click (event)->
                event.preventDefault()
    )
    .directive("chooseFile", ()->
        (scope, elm, attrs)->
            elm.click (event) ->
                input = elm.siblings().first()
                input.trigger('click')
    )
    .directive("ajaxUpload", ()->
        (scope, elm, attrs)->
            button_choose = elm.siblings().eq(0)
            button_cancel = elm.siblings().eq(1)
            button_upload = elm.siblings().eq(2)
            isLoaded = attrs.ajaxUpload
            scope.$watch isLoaded, (newValue, oldValue) ->
                if newValue
                    elm.fileupload {
                        dataType: 'json'
                        done: (e, data) ->
                            scope.$apply () ->
                                scope.cUser.img = data.result.user.img
                                scope.pUser.user.img = data.result.user.img

                            button_choose.prop 'disabled', false
                            button_upload.prop 'disabled', false
                            button_upload.html 'Upload'
                            button_upload.hide()
                            button_cancel.hide()
                        add: (e, data) ->
                            e.preventDefault()
                            # console.log data
                            loadingImage = window.loadImage(
                                data.files[0],
                                (img) ->
                                    scope.$apply () ->
                                        scope.pUserC.user.img = angular.copy scope.pUser.user.img
                                        scope.pUser.user.img = $(img)[0]
                                    button_upload.show()
                                    button_cancel.show()
                                    button_upload.click (event) ->
                                        event.preventDefault()
                                        button_choose.prop('disabled', true)
                                        button_upload.prop('disabled', true)
                                        button_upload.html 'Uploading...'
                                        data.submit()
                                    button_cancel.click (event) ->
                                        event.preventDefault()
                                        button_choose.prop 'disabled', false
                                        button_upload.prop 'disabled', false
                                        button_upload.hide()
                                        button_cancel.hide()
                                        scope.$apply () ->
                                            scope.pUser.user.img = scope.pUserC.user.img
                                {maxWidth: 100, maxHeight: 100}
                            )
                        submit: (e, data) ->
                            $this = $(@)
                            $.getJSON('/_/upload-url', (result) ->
                                data.url = result
                                $this.fileupload('send', data)
                            )
                            false
                    }
    )
    .directive("editProfile", () ->
        (scope, elm, attrs)->
            elm.click (event, sb) ->
                scope.$apply () ->
                    angular.copy scope.pUser, scope.pUserC
                input = elm.siblings('input').first()
                if input.length is 0
                    input = elm.siblings('div').first()
                    if input.length is 0
                        input = $('#bio')

                # console.log input

                button_save = "button[save-profile='"+input.attr('id')+"']"
                button_cancel = "button[reset-profile='"+input.attr('id')+"']"
                elm.hide()
                input.show()
                if not sb
                    $(button_save).show()
                    $(button_cancel).show()
    )
    .directive("resetProfile", () ->
        (scope, elm, attrs)->
            elm.click (event) ->
                scope.$apply () ->
                    angular.copy scope.pUserC, scope.pUser
                in_sel = "input#" + attrs.resetProfile
                input = $(in_sel)
                if input.length is 0
                    in_sel = "div#" + attrs.resetProfile
                    input = $(in_sel)

                div = input.siblings().first()
                if attrs.resetProfile is "bio"
                    $('#bio_t').val scope.pUser.user.bio
                    div = elm.siblings('div').first()
                button_save = elm.siblings('button').first()
                elm.hide()
                button_save.hide()
                input.hide()
                div.show()
    )
    .directive("saveProfile", () ->
        (scope, elm, attrs)->
            elm.click (event) ->
                in_sel = "input#" + attrs.saveProfile
                input = $(in_sel)
                isDob = false
                if input.length is 0
                    in_sel = "div#" + attrs.saveProfile
                    input = $(in_sel)
                    isDob = true
                div = input.siblings().first()
                if attrs.saveProfile is "bio"
                    scope.$apply () ->
                        scope.pUser.user.bio = $('#bio_t').val()
                    div = elm.siblings('div').first()
                button_reset = elm.siblings('button').first()
                elm.html('Saving...')
                elm.prop('disabled', true)

                scope.pUser.$update () ->
                    scope.pUser.user.dob = new Date(scope.pUser.user.dob_y, scope.pUser.user.dob_m, scope.pUser.user.dob_d)
                    elm.html('Save')
                    elm.prop('disabled', false)
                    elm.hide()
                    button_reset.hide()
                    input.hide()
                    div.show()
    )
    .directive('editAll', () ->
        (scope, elm, attrs)->
            elm.click (event) ->
                other_buttons = elm.siblings()
                elm.hide()
                other_buttons.show()
                editable = $('div[edit-profile]')
                scope.$apply () ->
                    angular.copy scope.pUser, scope.pUserC
                editable.trigger('click', [true])
    )
    .directive('saveAll', () ->
        (scope, elm, attrs)->
            elm.click (event) ->
                elm.html 'Saving...'
                # elm.prop 'disabled', true
                btns_tohide = elm.parent().children().not(':first-child')
                btns_tohide.prop 'disabled', true
                scope.pUser.$update () ->
                    scope.pUser.user.dob = new Date(scope.pUser.user.dob_y, scope.pUser.user.dob_m, scope.pUser.user.dob_d)
                    elm.html 'Save All'
                    btns_tohide.prop 'disabled', false
                    btn_toshow = elm.parent().children().first()
                    btns_totrig = $('button[reset-profile]')
                    btns_tohide.hide()
                    btn_toshow.show()
                    btns_totrig.trigger 'click'
    )
    .directive('cancelAll', () ->
        (scope, elm, attrs)->
            elm.click (event) ->
                btns_tohide = elm.parent().children().not(':first-child')
                btn_toshow = elm.parent().children().first()
                btns_totrig = $('button[reset-profile]')
                btns_tohide.hide()
                btn_toshow.show()
                scope.$apply () ->
                    angular.copy scope.pUserC, scope.pUser
                btns_totrig.trigger 'click'
    )
    .directive('textEditor', () ->
        (scope, elm, attr) ->
            # scope.editor = undefined
            isLoaded = attr.textEditor
            scope.$watch isLoaded, (newValue, oldValue) ->
                if newValue
                    # console.log elm.val()
                    # if not scope.editor
                    editor = new wysihtml5.Editor(attr.id, {
                        toolbar: attr.id+"-toolbar",
                        stylesheets: ["/css/reset.css","/css/editor.css"],
                        parserRules:  wysihtml5ParserRules
                    })

                    editor.on 'change', () ->
                        scope.$apply () ->
                            ev = 'editor:'+attr.id
                            scope.$emit ev, elm.val()
    )
    .directive('imgAdd', () ->
        (scope, elm, attr) ->
            elm.click (event) ->
                input = elm.siblings("input[type='file']")
                input.trigger('click')
    )
    .directive('imgAjax', ['$timeout', ($timeout) ->
        (scope, elm, attr) ->
            elm.fileupload {
                dataType: 'json'
                add: (e, data) ->
                    # console.log data
                    # if length < 1
                    window.loadImage(
                        data.files[0],
                        (img) ->
                            # data.context = $('.item-img-upload')
                            scope.$apply () ->
                                scope.opt.disabled = true
                                scope.opt.th.push img
                                scope.opt.prog.push opacity: 1
                                id = scope.item.data.imgs.push data
                                scope.item.data.imgs[id-1].context = {id: id-1, ctx: $('.item-img-upload')}
                                scope.opt.id.push id-1
                        ,{maxWidth: 80, maxHeight: 80, canvas: true}
                    )
                submit: (e, data) ->
                    $this = $(@)
                    $.getJSON('/_/upload-url?q=item', (result) ->
                        data.url = result
                        $this.fileupload('send', data)
                    )
                    false
                done: (e, data) ->
                    idx = scope.opt.id.indexOf data.context.id
                    href = $('<a/>').attr('href', data.result.img.url).html(scope.item.data.imgs[idx].files[0].name)
                    img_obj = 
                        files: [
                            name: href[0]
                            size: scope.item.data.imgs[idx].files[0].size
                        ]
                        key: data.result.img.key
                        del_url: data.result.img.del_url
                    $timeout () ->
                        scope.$apply () ->
                            scope.opt.prog.splice idx, 1, {opacity: 0}
                            scope.item.data.imgs.splice idx, 1, img_obj
                            scope.opt.th.splice idx, 1, $('<img/>').attr('src', data.result.img.th_small_url)[0]
                    , 1000
            }

            elm.bind 'fileuploadprogress', (e, data) ->
                progress = parseInt(data.loaded / data.total * 100, 10)
                prog = "#progress"+data.context.id
                data.context.ctx.find(prog).children('.meter').animate {width: progress+'%'}
    ])
    .directive('imgUpload', () ->
        (scope, elm, attr) ->
            ind = scope.$eval attr.imgUpload
            elm.click (event) ->
                elm.html 'Uploading...'
                elm.prop 'disabled', true
                idx = scope.opt.id.indexOf ind
                data = scope.item.data.imgs[idx]
                data.submit()
    )
    .directive('imgUploadCancel', () ->
        (scope, elm, attr) ->
            ind = scope.$eval attr.imgUploadCancel
            elm.click (event) ->
                idx = scope.opt.id.indexOf ind
                scope.$apply () ->
                    scope.opt.disabled = false
                    scope.opt.prog.splice idx, 1
                    scope.opt.id.splice idx, 1
                    scope.item.data.imgs.splice idx, 1
                    scope.opt.th.splice idx, 1
    )
    .directive('imgUploadDelete', ["$http", ($http) ->
        (scope, elm, attr) ->
            ind = scope.$eval attr.imgUploadDelete
            elm.click (event) ->
                idx = scope.opt.id.indexOf ind
                $http
                    .delete(scope.item.data.imgs[idx].del_url)
                    .success (data, status, headers, config) ->
                        scope.opt.disabled = false
                        scope.opt.prog.splice idx, 1
                        scope.opt.id.splice idx, 1
                        scope.item.data.imgs.splice idx, 1
                        scope.opt.th.splice idx, 1
                    .error (data, status, headers, config) ->
                        console.log status
    ])
    .directive('viewMessage', () ->
        (scope, elm, attr) ->
            ind = scope.$eval attr.viewMessage
            elm.click (event) ->
                event.preventDefault()
                scope.$apply () ->
                    scope.msgViw.item = scope.pm.items[ind]
                    scope.msgViw.user = scope.pm.users[ind]
                    scope.msgViw.msg = scope.pm.msgs[ind]
                    $('#viewMessageModal').reveal(
                        closed: () ->
                            scope.$apply () ->
                                delete scope.msgViw.item
                                delete scope.msgViw.user
                                delete scope.msgViw.msg
                    )
                    if not scope.pm.msgs[ind].read
                        scope.readit(ind)
                false
    )
    .directive('loadMore', ['$http', ($http) ->
        (scope, elm, attr) ->
            elm.click (event) ->
                scope.loadmore = true
                $http
                    .get(scope.shops.next_url)
                    .success (data, status, headers, config) ->
                        # scope.$apply () ->
                        scope.loadmore = false
                        scope.shops.next_url = data.next_url
                        scope.shops.items = scope.shops.items.concat data.items
                        scope.shops.users = scope.shops.users.concat data.users
    ])
    .directive('itemDetails', () ->
        (scope, elm, attr) ->
            ind = scope.$eval attr.itemDetails
            elm.click (event) ->
                event.preventDefault()
                scope.$apply () ->
                    scope.itemDetails.item = scope.shops.items[ind]
                    scope.itemDetails.user = scope.shops.users[ind]
                    scope.itemDetails.imgs = scope.shops.imgs[ind]
                    $('#itemDetailsModal').reveal()
                false
    )
    .directive('itemDetailshp', () ->
        (scope, elm, attr) ->
            ind = scope.$eval attr.itemDetailshp
            elm.click (event) ->
                event.preventDefault()
                scope.$apply () ->
                    scope.itemDetails.item = scope.home.pops.items[ind]
                    scope.itemDetails.user = scope.home.pops.users[ind]
                    scope.itemDetails.imgs = scope.home.pops.imgs[ind]
                    $('#itemDetailsModal').reveal()
                false
    )
    .directive('itemDetailshn', () ->
        (scope, elm, attr) ->
            ind = scope.$eval attr.itemDetailshn
            elm.click (event) ->
                event.preventDefault()
                scope.$apply () ->
                    scope.itemDetails.item = scope.home.newest.items[ind]
                    scope.itemDetails.user = scope.home.newest.users[ind]
                    scope.itemDetails.imgs = scope.home.newest.imgs[ind]
                    $('#itemDetailsModal').reveal()
                false
    )
    .directive('itemSearch', ['$timeout', '$http', ($timeout, $http) ->
        (scope, elm, attr) ->
            promise = undefined
            call = undefined
            elm.bind 'textchange', () ->
                if call
                    call.reject 'canceled'
                $timeout.cancel promise
                promise = $timeout () ->
                    if elm.val().length > 2
                        call = $http.get '/_/items/search?q=' + elm.val()
                        call.success (data, status, headers, config) ->
                            call = undefined
                            console.log data
                , 1000
    ])
    .directive('itemMessage', () ->
        (scope, elm, attr) ->
            ind = scope.$eval attr.itemMessage
            elm.click (event) ->
                event.preventDefault()
                scope.$apply () ->
                    scope.msgItm.ready = true
                    scope.msgItm.item = scope.shops.items[ind]
                    scope.msgItm.rec = scope.shops.users[ind]
                    $('#newMessageItemModal').reveal({
                        closeOnBackgroundClick: false
                        animationSpeed: 200
                        closed: () ->
                            scope.$apply () ->
                                scope.msgItm.ready = false
                                delete scope.msgItm.content
                                delete scope.msgItm.title
                                delete scope.msgItm.item
                                delete scope.msgItm.rec
                    })
                false
    )
    .directive('composeMessage', () ->
        (scope, elm, attr) ->
            elm.click (event) ->
                event.preventDefault()
                scope.$apply () ->
                    scope.msgNew.ready = true
                    $('#newMessageModal').reveal({
                        closeOnBackgroundClick: false
                        animationSpeed: 200
                        closed: () ->
                            scope.$apply () ->
                                scope.msgNew.ready = false
                                delete scope.msgNew.content
                                delete scope.msgNew.title
                                delete scope.msgNew.to
                    })
                false
    )
    .directive('replyMessage', () ->
        (scope, elm, attr) ->
            ind = scope.$eval attr.replyMessage
            elm.click (event) ->
                event.preventDefault()
                scope.$apply () ->
                    scope.msgNew.ready = true
                    scope.msgNew.reply = true
                    scope.msgNew.to = scope.pm.users[ind]
                    $('#newMessageModal').reveal({
                        closeOnBackgroundClick: false
                        animationSpeed: 200
                        closed: () ->
                            scope.$apply () ->
                                scope.msgNew.ready = false
                                delete scope.msgNew.content
                                delete scope.msgNew.title
                                delete scope.msgNew.to
                                delete scope.msgNew.reply
                    })
                false
    )
    .directive('itemSendMessage', ['$http', ($http) ->
        (scope, elm, attr) ->
            elm.click (event) ->
                if scope.message.ready
                    elm.prop 'disabled', true
                    elm.html "<i class='icon-ok icon-large'></i> Sending..."
                    $http
                        .post('/_/message/new', scope.message)
                        .success (data, status, headers, config) ->
                            if data.status is "success"
                                elm.prop 'disabled', false
                                elm.html "<i class='icon-ok icon-large'></i> Send"
                                $('#newMessageModal').trigger('reveal:close')
    ])